package com.ynunicom.midplatform.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Utr 工具类
 *
 * @author duwei
 * @version 2018/5/18 9:21
 */
@Slf4j
public class UrlUtil {


    public static String urlEncodeUTF8(String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("编码 Url 失败!", e);
            throw new UnsupportedOperationException("编码 Url 失败!", e);
        }

    }

    public static String spliceUrlParam(String url, Map<String, String> params) {

        if (params == null) {
            return url;
        }

        String paramString = params.entrySet().stream()
                .map(p -> p.getKey() + "=" + p.getValue())
                .reduce((p1, p2) -> p1 + "&" + p2)
                .orElse("");
        if (url.contains("?") && url.indexOf("?") < url.length() - 1) {
            url += "&";
        } else if (!url.contains("?")) {
            url += "?";
        }
        return url + urlEncodeUTF8(paramString);
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>(2);
        params.put("aaa", "http://www.duwei.com");
        params.put("bbb", "222");
        String url = "http://www.duwei.com?";
        System.out.println(spliceUrlParam(url, params));
    }
}
